// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package config

import (
	"fmt"
	"os"

	"gitcode.com/openseaotter/so_server/utils"
	"gopkg.in/yaml.v3"
)

type RemoteConfig struct {
	RemoteId    string `yaml:"remoteId"`
	RemoteAddr  string `yaml:"remoteAddr"`
	ProjectId   string `yaml:"projectId"`
	ShareSecret string `yaml:"shareSecret"`
}

type ServerConfig struct {
	Domain      string          `yaml:"domain"`
	ServicePort uint16          `yaml:"servicePort"`
	HttpPort    uint16          `yaml:"httpPort"`    //http端口 默认80
	HttpTlsPort uint16          `yaml:"httpTlsPort"` //https端口 默认443
	TlsCertFile string          `yaml:"tlsCertFile"`
	TlsKeyFile  string          `ymal:"tlsKeyFile"`
	SuperToken  string          `yaml:"superToken"`
	RemoteList  []*RemoteConfig `yaml:"remoteList"`
}

func (cfg *ServerConfig) GetRemote(remoteId string) (*RemoteConfig, bool) {
	for _, remoteCfg := range cfg.RemoteList {
		if remoteCfg.RemoteId == remoteId {
			return remoteCfg, true
		}
	}
	return nil, false
}

func ReadServerConfig() (*ServerConfig, error) {
	data, err := os.ReadFile(utils.CONFIG_FILE_PATH)
	if err != nil {
		return nil, err
	}
	cfg := &ServerConfig{}
	err = yaml.Unmarshal(data, cfg)
	if err != nil {
		return nil, err
	}
	if cfg.HttpTlsPort > 0 && (cfg.TlsCertFile == "" || cfg.TlsKeyFile == "") {
		return nil, fmt.Errorf("wrong tls config")
	}
	if cfg.RemoteList == nil {
		cfg.RemoteList = []*RemoteConfig{}
	}
	return cfg, nil
}

func WriteServerConfig(cfg *ServerConfig) error {
	if cfg.RemoteList == nil {
		cfg.RemoteList = []*RemoteConfig{}
	}
	err := utils.InitUserAndGroup()
	if err != nil {
		return err
	}
	data, err := yaml.Marshal(cfg)
	if err != nil {
		return err
	}
	os.MkdirAll(utils.CONFIG_DIR_PATH, 0755) //skip error check
	err = os.WriteFile(utils.CONFIG_FILE_PATH, data, 0644)
	if err != nil {
		return err
	}
	uid, gid, err := utils.GetUidAndGid()
	if err == nil {
		os.Chown(utils.CONFIG_DIR_PATH, uid, gid)  //skip error check
		os.Chown(utils.CONFIG_FILE_PATH, uid, gid) //skip error check
	}
	return nil
}
